from PySide6 import QtCore, QtWidgets,QtGui
from PySide6.QtCharts import *
from numpy import sin
class MyChartView(QChartView):
    def __init__(self,chart,parent=None) :
        super().__init__(chart,parent)
        self.m_isTouching=False
        self.setRubberBand(QChartView.RectangleRubberBand)
    def viewportEvent(self,event):
        if (event.type() == QtCore.QEvent.TouchBegin):
            # By default touch events are converted to mouse events. So
            # after this event we will get a mouse event also but we want
            # to handle touch events as gestures only. So we need this safeguard
            # to block mouse events that are actually generated from touch.
            self.m_isTouching = True

            # Turn off animations when handling gestures they
            # will only slow us down.
            self.chart().setAnimationOptions(QtCharts.QChart.NoAnimation)
        return super().viewportEvent(event)

    def mousePressEvent(self,event):
        if (self.m_isTouching):
            return
        super().mousePressEvent(event)

    def mouseMoveEvent(self,event):
        if (self.m_isTouching):
            return;
        super().mouseMoveEvent(event);

    def mouseReleaseEvent(self,event):
        if (self.m_isTouching):
            self.m_isTouching = False;

        # Because we disabled animations when touch event was detected
        # we must put them back on.
        # self.chart().setAnimationOptions(QChart.SeriesAnimations);
        super().mouseReleaseEvent(event);
    def keyPressEvent(self,event):
        if(event.key()==QtCore.Qt.Key_Plus):
            self.chart().zoomIn();
        elif(event.key()==QtCore.Qt.Key_Minus):
            self.chart().zoomOut();
        elif(event.key()==QtCore.Qt.Key_Left):
            self.chart().scroll(-10, 0);
        elif(event.key()==QtCore.Qt.Key_Right):
            self.chart().scroll(10, 0);
        elif(event.key()==QtCore.Qt.Key_Up):
            self.chart().scroll(0, 10);
        elif(event.key()==QtCore.Qt.Key_Down):
            self.chart().scroll(0, -10);
        else:
            super().keyPressEvent(event);
if __name__ == "__main__":
    a = QtWidgets.QApplication()
    a.lastWindowClosed.connect(a.quit)
    series = QLineSeries()
    for i in range(500):
        series.append(float(i), sin(3.14 / 50 * i) * 100)
    chart =QChart()
    chart.addSeries(series);
    chart.setTitle("Zoom in/out example");
    # chart.setAnimationOptions(QtCharts.QChart.SeriesAnimations);
    chart.legend().hide();
    chart.createDefaultAxes();
    chartView = MyChartView(chart);
    chartView.setRenderHint(QtGui.QPainter.Antialiasing);

    window=QtWidgets.QMainWindow()
    window.setCentralWidget(chartView);
    window.resize(400, 300);
    window.grabGesture(QtCore.Qt.PanGesture);
    window.grabGesture(QtCore.Qt.PinchGesture);
    window.show()
    a.exec()